﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using EHTSaleManager.Code.BLL;
using System.Data;
using EHTSaleManager.Code.Entity;
using System.Web.Profile;
using EHTSaleManager.Code.Utility;
using System.Web.UI.HtmlControls;

namespace EHTSaleManager.UICustomer
{
    public partial class CustomerEditOrder : System.Web.UI.Page
    {
        public String CustomerID = "";
        public Int32 OrderID = -1;
        public Int32 OrderState = HangSo.ORDER_STATE_ERROR;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["OrderID"] != null)
            {
                try
                {
                    OrderID = Int32.Parse(Request.QueryString["OrderID"].ToString());
                }
                catch (Exception)
                {
                    OrderID = -1;
                }

            }
            if (!Page.IsPostBack)
            {
                GetAllRegion();
                GetOrder();
            }
        }

        private void GetAllRegion()
        {
            DataSet dsRegion = RegionProvider.GetRegions();
            this.ddlReceivedRegion.DataValueField = "RegionID";
            this.ddlReceivedRegion.DataTextField = "RegionName";
            this.ddlReceivedRegion.DataSource = dsRegion;
            this.ddlReceivedRegion.DataBind();
        }

        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;

            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }

        protected void ddlReceivedRegion_DataBound(object sender, EventArgs e)
        {
            this.ddlReceivedRegion.Items.Insert(0, new ListItem("select region ...", "-1"));
        }


        private void GetOrder()
        {
            Order theOrders = OrderProvider.GetOrderByOrderID(OrderID);
            if (theOrders != null)
            {
                if (theOrders.OrderState == HangSo.ORDER_STATE_APPENDING)
                {
                    EnabledOrDisabledControl(true);
                    OrderState = HangSo.ORDER_STATE_APPENDING;
                }
                else
                {
                    EnabledOrDisabledControl(false);
                    OrderState = HangSo.ORDER_STATE_SHIPPING;
                }
                txtReceivedName.Text = theOrders.ReceivedName.ToString();
                txtReceivedAddress.Text = theOrders.ReceivedAddress.ToString();
                txtReceivedCity.Text = theOrders.ReceivedCity.ToString();
                txtReceicedPhone.Text = theOrders.ReceicedPhone.ToString();
                txtPostCode.Text = theOrders.ReceivedPostalCode.ToString();
                ddlReceivedRegion.SelectedIndex = ddlReceivedRegion.Items.IndexOf(ddlReceivedRegion.Items.FindByValue(theOrders.ReceivedRegionID.ToString()));
                cdRequredDate.SelectedDate = theOrders.RequireDate;
                lblServiceCostValue.Text = theOrders.ServiceCost.ToString();
                DataSet dsOrderDetails = OrderDetaiProvider.GetOrderDetailByOrderID(OrderID);
                rOrderDetails.DataSource = dsOrderDetails;
                rOrderDetails.DataBind();
                HttpContext.Current.Session["ASPNETShoppingCart"] = null; // xóa thông tin ShoppingCart
                int productID;
                float quantity;
                for (int i = 0; i < dsOrderDetails.Tables[0].Rows.Count; i++)
                {
                    productID = int.Parse(dsOrderDetails.Tables[0].Rows[i]["ProductID"].ToString());
                    quantity = float.Parse(dsOrderDetails.Tables[0].Rows[i]["Quantity"].ToString());
                    ShoppingCart.Instance.AddItem(productID,1);
                    ShoppingCart.Instance.SetItemQuantity(productID, quantity);
                }
            }
        }

        private void EnabledOrDisabledControl(bool IsEnabled)
        {
            btnDelete.Visible = IsEnabled;
            btnSave.Visible = IsEnabled;
            txtReceivedName.Enabled = IsEnabled;
            txtReceivedAddress.Enabled = IsEnabled;
            txtReceicedPhone.Enabled = IsEnabled;
            txtReceivedCity.Enabled = IsEnabled;
            txtPostCode.Enabled = IsEnabled;
            ddlReceivedRegion.Enabled = IsEnabled;
            cdRequredDate.Enabled = IsEnabled;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {
                UpdateOrder();
                Response.Redirect("~/UICustomer/CustomerHistoryOfOrder.aspx");

            }
        }

        private void UpdateOrder()
        {
            MembershipUser theUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            Order theOrder = new Order();
            theOrder.BillPictureUrl = "";
            theOrder.CustomerID = theUser.ProviderUserKey.ToString();
            theOrder.OrderID = OrderID;
            theOrder.OrderState = HangSo.ORDER_STATE_APPENDING;
            theOrder.ReceicedPhone = this.txtReceicedPhone.Text.Trim();
            theOrder.ReceivedAddress = this.txtReceivedAddress.Text.Trim();
            theOrder.ReceivedCity = this.txtReceivedCity.Text.Trim();
            theOrder.ReceivedName = this.txtReceivedName.Text.Trim();
            theOrder.ReceivedPostalCode = this.txtPostCode.Text.Trim();
            theOrder.ReceivedRegionID = Int32.Parse(this.ddlReceivedRegion.SelectedValue.ToString());
            theOrder.RequireDate = cdRequredDate.SelectedDate;
            theOrder.ServiceCost = float.Parse(lblServiceCostValue.Text.ToString().Trim());
            theOrder.TotalAmount = ShoppingCart.Instance.GetSubTotal();
            // Update order infomation
            OrderProvider.UIOrder(theOrder, false);
        }

        protected void rOrderDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            String sAction = e.CommandName.ToString();
            String sOrderDetailID = e.CommandArgument.ToString();
            Int32 iProductID = -1;
            if (sAction == "DeleteOrderDetail")
            {
                OrderDetail theOrderDetail = OrderDetaiProvider.GetOrderDetailByID(Int32.Parse(sOrderDetailID));
                if (theOrderDetail != null)
                {
                    iProductID = theOrderDetail.ProductID;
                    ShoppingCart.Instance.RemoveItem(iProductID);
                    OrderDetaiProvider.DeleteOrderDetailOderByID(Int32.Parse(sOrderDetailID));
                    UpdateOrder();
                    DataSet dsOrderDetails = OrderDetaiProvider.GetOrderDetailByOrderID(OrderID);
                    if (dsOrderDetails.Tables[0].Rows.Count == 0)
                    {
                        Order theOrder = OrderProvider.GetOrderByOrderID(OrderID);
                        float fServiceCost = 0;
                        if (theOrder != null)
                        {
                            fServiceCost = float.Parse(theOrder.ServiceCost.ToString().Trim());
                        }

                        // Delete order
                        OrderProvider.DeleteOderByOrderID(OrderID);

                        // cập nhật vào tài khoản Customer phí dịch vụ
                        ProfileBase theProfile = ProfileBase.Create(HttpContext.Current.User.Identity.Name);
                        float toltalAccountCurrent = float.Parse(theProfile.GetPropertyValue("ToltalAccount").ToString()); // tổng tài khoản hiện tại
                        float toltalAccountNow = toltalAccountCurrent - fServiceCost; // tổng tài khoảng thay thế
                        theProfile.SetPropertyValue("ToltalAccount", toltalAccountNow);
                        theProfile.Save();
                        Response.Redirect("~/UICustomer/CustomerHistoryOfOrder.aspx");
                    }
                    else
                    {
                        GetOrder();
                    }
                }
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UICustomer/CustomerHistoryOfOrder.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UICustomer/CustomerComfirmDeleteOrder.aspx?OrderID=" + OrderID);
        }

        protected void rOrderDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HtmlTableCell TitleDelete = (HtmlTableCell)e.Item.FindControl("tdTitleDelete");
            HtmlTableCell ActionDelete = (HtmlTableCell)e.Item.FindControl("tdActionDelete");
            if (ActionDelete != null)
            {
                if (OrderState == HangSo.ORDER_STATE_APPENDING)
                {
                    ActionDelete.Style["display"] = "";
                }
                else
                {
                    ActionDelete.Style["display"] = "none";
                }
            }
            if (TitleDelete != null)
            {
                if (OrderState == HangSo.ORDER_STATE_APPENDING)
                {
                    TitleDelete.Style["display"] = "";
                }
                else
                {
                    TitleDelete.Style["display"] = "none";
                }
            }
        }
    }
}